package com.njupt.Array;

import java.util.*;

/**
 * 904. 水果成篮
 * 本质上是找至多只有两种元素的最长字串的长度
 */
public class TotalFruit {


    /**
     * 滑动窗口法
      * @param fruits
     * @return
     */
    public int totalFruit1(int[] fruits){
        int left=0,right = 0;
        int len = 0;

        Map<Integer, Integer> map = new HashMap<>();
        for ( right = 0; right < fruits.length; right++) {
            map.put(fruits[right],map.getOrDefault(fruits[right],0)+1);
            while(map.size()>2){
                map.put(fruits[left],map.get(fruits[left])-1);
                if(map.get(fruits[left]) == 0){
                    map.remove(fruits[left]);
                }
                left++;
            }
            len = Math.max(len,right-left+1);
        }
        return len;
    }

    public int totalFruit2(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();

        int left = 0, ans = 0;
        for (int right = 0; right < n; ++right) {
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            while (cnt.size() > 2) {
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }







    public int totalFruit(int[] fruits) {
//        if(fruits.length==1 || fruits.length==1 && fruits[0] == 0){
//            return 1;
//        }

        Set<Integer> integerSet = new HashSet<>();
        int max = 0;
        int currentLen = 0;
        for (int i = 0; i < fruits.length; i++) {
            for (int j = i; j < fruits.length; j++) {

                int[] subInts = Arrays.copyOfRange(fruits, i, j + 1);
                if(calSetKind(subInts,integerSet)) {
                    currentLen = j -i +1;
                    if(currentLen>max){
                        max = currentLen;
                    }
//
                }
                integerSet.clear();

            }
        }

        return max;
    }

    public boolean calSetKind(int[] nums,Set set){
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
            if(set.size()>2){
                return false;
            }
        }
        if(set.size() == 2 || set.size() == 1){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TotalFruit test = new TotalFruit();
        int[] fruits = {0,1,2,2};
        System.out.println(test.totalFruit1(fruits));
    }


}
